package com.ay.selfservicemachine.http.websocket;

import java.util.ArrayList;
import java.util.List;

import okio.ByteString;

public class SocketManger {


    private static List<SocketClient> socketClients = new ArrayList<>();

    public static void startClient(int from, String url, SocketClient.ClientAction clientAction) {
        if (!isExist(from)) {
            socketClients.add(new SocketClient(from, url, clientAction));
        }
    }

    public static void send(int from,String message){
        for (int i = 0; i < socketClients.size(); i++) {
            if (from == socketClients.get(i).getFrom()) {
                socketClients.get(i).getWebSocket().send(message);
            }
        }
    }

    public static void send(int from, ByteString message){
        for (int i = 0; i < socketClients.size(); i++) {
            if (from == socketClients.get(i).getFrom()) {
                socketClients.get(i).getWebSocket().send(message);
            }
        }
    }

    /**
     * 判断Socket是否存在
     */
    private static boolean isExist(int from) {
        for (int i = 0; i < socketClients.size(); i++) {
            if (from == socketClients.get(i).getFrom()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 关闭指定Socket
     */
    public static void cancelSocket(int from) {
        for (int i = 0; i < socketClients.size(); i++) {
            if (from == socketClients.get(i).getFrom()) {
                socketClients.get(i).cancel();
                socketClients.remove(i);
            }
        }
    }

    /**
     * 关闭所有Socket
     */
    public static void cancelSocketAll() {
        for (int i = 0; i < socketClients.size(); i++) {
            socketClients.get(i).cancel();
        }
        socketClients.clear();
    }
}
